<template>
  <div class="h-full w-full cont_bg flex items-center justify-center">
    <div
      class="login_box h-[50%] w-[30%] rounded-xl p-5 flex items-center justify-center box-border"
    >
      <el-form
        ref="ruleFormRef"
        :model="loginFrom"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm w-full"
        status-icon
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginFrom.username"
            placeholder="请输入用户名称、手机号或工号"
          >
            <template #prepend>
              <span class="iconfont icon-yonghuming"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="loginFrom.password" placeholder="请输入密码">
            <template #prepend>
              <span class="iconfont icon-mima"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="verificationCode">
          <p class="flex items-center w-full">
            <el-input
              class="flex-1"
              v-model="loginFrom.verificationCode"
              placeholder="请输入前端验证码"
            >
              <template #prepend>
                <span class="iconfont icon-yanzhengma"></span>
              </template>
            </el-input>
            <span @click="sidentifyClick"
              ><sidentify :identifyCode="identifyCode"
            /></span>
          </p>
        </el-form-item>
        <el-form-item prop="captcha">
          <p class="flex items-center w-full">
            <el-input
              class="flex-1"
              v-model="loginFrom.captcha"
              placeholder="请输入后端验证码"
            >
              <template #prepend>
                <span class="iconfont icon-yanzhengma"></span>
              </template>
            </el-input>
            <span class="w-[110px] h-[30px] rounded-sm ml-2">
              <img
                :src="codeUrl"
                @click="getCode"
                class="w-full h-full rounded-[4px]"
                title="图形验证码,点击刷新"
                alt="图形验证码"
              />
            </span>
          </p>
        </el-form-item>
        <el-form-item>
          <p class="flex items-center justify-between w-full">
            <el-checkbox v-model="remember" label="记住密码" size="large" />
            <span @click="forgetPassword">忘记密码</span>
          </p>
        </el-form-item>
        <el-form-item class="from_btn">
          <el-button type="primary" @click="submitForm(ruleFormRef)"> 登录 </el-button>
        </el-form-item>
        <el-form-item>
          <p>
            <span class="text-[#e2e2e2a1]">还没有账号？立即>></span
            ><span @click="register">注册</span>
          </p>
        </el-form-item>
      </el-form>
    </div>
    <!-- <el-button @click="handleImport"> 登录 </el-button> -->
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick, onBeforeUnmount } from "vue";
import { _login, _getUserInfo, _getCode } from "@/api/login";
import { encodeStr } from "@/utils/publicKey";
import { LoginFrom, LoginPublic } from "@/types/login";
import type { FormInstance, FormRules } from "element-plus";
import sidentify from "@/components/sidentify/index.vue";
import { randomVerificationCode } from "@/utils/utils";
import { ElMessage } from "element-plus";
import store from "@/store";
import { LoginTokenObj } from "@/types/type";
import router from "@/router";
import { cookie } from "@/utils/local";

const ruleFormRef = ref<FormInstance>();
const identifyCode = ref<string>(randomVerificationCode());
const loginFrom = ref<LoginFrom>({
  username: "", //用户名称或者手机号或工号
  password: "", //密码
  // grantType: "", //认证类型(password（登录）,refresh_token（刷新token）)
  // platform: "", //登录平台(后台用户--ADMIN,前台用户--APP)
  // refreshToken: "", //刷新tokne,没有则不传
  verificationCode: "", //验证码
  captcha: "", //验证码
});
// 是否记住密码
const remember = ref<boolean>(true);
// 登录
async function submitForm(formEl: FormInstance | undefined) {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let publicKey = import.meta.env.VITE_APP_publicKey;
      const res: any = await _login({
        username: encodeStr(loginFrom.value.username, publicKey),
        password: encodeStr(loginFrom.value.password, publicKey),
        grantType: "password",
        platform: "FRONT",
      });
      if (res?.code == 10000) {
        let newtokenObj: LoginTokenObj = {
          ...res?.data,
          expiresIn: res?.expiresIn ?? 43200,
          tokenExpirationTime: new Date(),
        };
        store.commit("setTokenObj", newtokenObj);
        getUserInfo();
      } else {
        ElMessage.warning(
          res?.message ? res?.message : "登录失败，请确认账户及密码或网路状态！"
        );
      }
    }
  });
}
// 获取用户信息
let loginLoading = ref<boolean>(false);
const getUserInfo = async () => {
  try {
    // 事件处理程序
    loginLoading.value = true;
    const res: any = await _getUserInfo();
    if (res?.code == 10000) {
      store.commit("setUserInfo", res?.data);
      ElMessage.success(res?.message ? res?.message : "获取用户信息成功！");
      // 实现记住密码功能，密码1天过期
      if (remember.value) {
        cookie.set("username", loginFrom.value.username, 1);
        cookie.set("password", loginFrom.value.password, 1);
      } else {
        cookie.remove("username");
        cookie.remove("password");
      }
      router.replace("/");
    } else {
      store.commit("setTokenObj", {});
      ElMessage.warning(
        res?.message ? res?.message : "获取用户信息失败，请尝试重新登录！"
      );
    }
  } catch (err) {
    // 错误事件处理程序（报错时执行）
    console.error(err);
  } finally {
    // 事件处理程序（报错或正常都会执行）
    loginLoading.value = false;
  }
};
const codeUrl = ref<string>();
const imgUUID = ref<string>();
// 获取验证码
const getCode = async () => {
  try {
    let src: any = await _getCode();
    console.log("更换验证码", src);
    if (src?.code == 10000) {
      codeUrl.value = "data:image/jpeg;base64," + src?.data?.img;
      imgUUID.value = src?.data?.imgUUID;
    } else {
      ElMessage.warning(src?.message ? src?.message : "获取验证码失败！");
    }
  } catch (err) {
    console.error(err);
  }
};
// 忘记密码
function forgetPassword() {}
// 注册账号
function register() {}
// 刷新验证码
function sidentifyClick() {
  identifyCode.value = randomVerificationCode();
  loginFrom.value.verificationCode = identifyCode.value;
}
// 校验验证码是否正确
const validatePwdBlur = (rule: any, value: any, callback: any) => {
  if (value === identifyCode?.value) callback();
  callback(new Error("验证码不正确，请重新输入！"));
};
onMounted(() => {
  nextTick(() => {
    getCode();
    // 上一次登录勾选记住密码时存在值就直接回显
    if (cookie.get("username") && cookie.get("password")) {
      loginFrom.value.username = cookie.get("username");
      loginFrom.value.password = cookie.get("password");
    }
    loginFrom.value.verificationCode = identifyCode.value;
  });
  document.addEventListener("keydown", (event: any) => {
    if (event.keyCode === 13) {
      submitForm(ruleFormRef.value);
    }
  });
});
onBeforeUnmount(() => {
  document.removeEventListener("keydown", (event: any) => {
    if (event.keyCode === 13) {
      submitForm(ruleFormRef.value);
    }
  });
});
const rules = reactive<FormRules<LoginPublic>>({
  username: [
    {
      required: true,
      message: "请输入用户名称、手机号或工号",
      trigger: ["change", "blur"],
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["change", "blur"],
    },
  ],
  verificationCode: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "change",
    },
    { validator: validatePwdBlur, trigger: "blur" },
  ],
  captcha: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "change",
    },
  ],
});
</script>

<style lang="scss" scoped>
.cont_bg {
  background: url("../../assets//bg.jpeg") no-repeat center center fixed;
  background-size: cover;
  .login_box {
    background: linear-gradient(to bottom left, #00c9a9, #0085ea);
  }
  :deep(.el-form-item__label) {
    color: #fff !important;
  }
  :deep(.el-checkbox__label) {
    color: #fff !important;
  }
  :deep(.from_btn) {
    width: 100%;
    .el-form-item__content {
      display: flex;
      align-items: center;
      justify-content: center;
      .el-button {
        flex: 1;
      }
    }
  }
}
</style>
